package com.zretc.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author 周文涛
 * 2020年8月21日11:44:05
 *  判断用户是否拥有角色访问
 */
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collections) throws AccessDeniedException, InsufficientAuthenticationException {

        // 迭代配置属性列表
        for (ConfigAttribute collection : collections) {
            // 从属性中获取需要的角色
            String needRole = collection.getAttribute();
            // 判断是否是固定角色 ROLE_LOGIN
            if("ROLE_LOGIN".equals(needRole)){
                // 判断是否登录
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录，请登录!");
                }
                else
                    return;
            }

            // 获取认证的用户角色列表
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            // 迭代认证列表
            for (GrantedAuthority authority : authorities) {
                // 判断是否拥有角色
                if(authority.getAuthority().equals(needRole)){
                    // 如果拥有角色，则放行
                    return;
                }

            }

        }

        throw new AccessDeniedException("权限不足，请联系管理员!");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
